-- @name 恶魔虫谷自动化模块
-- @version 1.0.0
-- @description 恶魔虫谷状态监测与自动传送系统
-- @require modules/inventory.lua
-- @require modules/shop.lua
-- @require modules/movement.lua
-- @require modules/combat.lua

local ConfigLoader = require("config.loader")
local Settings = require("config.settings")
local config = ConfigLoader.load(Settings.CURRENT_GAME)
local logger = require "utils.logger"
local stateManager = require "utils.state_manager"
local inventory = require "modules.inventory"
local shop = require "modules.shop"
local movement = require "modules.movement"
local combat = require "modules.combat"
local tslib = require "TSLib"

local function check_in_devil_valley()
    logger.info("正在检测恶魔虫谷")
    -- 恶魔虫谷地图特征检测
    return movement.isInDevilWormValley()
end

local function main()
    logger.info("运行进入恶魔虫谷脚本")
    while true do
        local success, err = pcall(function()
            if not check_in_devil_valley() then
                movement.useRandomStone()
                mSleep(1000)
                movement.useTownStone()

                -- 向南方向移动
                movement.dragDirection('south', 2000)

                local attempts = 0
                local max_attempts = config.COLOR_MATCH.ATTEMPTS or 3
                while attempts < max_attempts do
                    local x,y = findMultiColorInRegionFuzzy(0xc5614b, "20|-18|0xd0af92,22|-3|0xa48d41,19|9|0xaa7a33,20|26|0x0b230e", 95, 287, 322, 1200, 631, { orient = 5,max_miss = 3 })
                    
                    if x ~= -1 then
                        logger.debug(string.format("第%d次比色成功", attempts+1))
                        movement.click(x, y)
                        movement.click(802,551)
                        if movement.isInDevilWormValley() then
                            logger.info("已到达恶魔虫谷出口")
                            combat.startAutoAttack()
                        end
                        break
                    else
                        attempts = attempts + 1
                        logger.warn(string.format("比色失败，已尝试%d次", attempts))
                        mSleep(config.COLOR_MATCH.RETRY_INTERVAL or 1000)
                    end
                end
            else
                logger.info("当前已在恶魔虫谷中")
            end
        end)
        
        -- 使用独立配置项
        local checkInterval = 5000
        logger.debug("等待" .. checkInterval/1000 .. "秒后重新检测")
        mSleep(checkInterval)
    end
end

return {
    run = main
}